const Base = require('./base');
const schedule = require('node-schedule'); 
const { get_music, downloadMp3 } = require('../mu/MusicDownUtil');
const load = require('audio-loader');

class Mp3 extends Base {

    async playlist() { 
        let rel = await  this.$model.mp3.getPlaylist()
        this.$show(rel)
    }

    async _init() {
        try {  
            const jobs = schedule.scheduledJobs
            // console.log('jobs',jobs)
            schedule.scheduleJob('get_music', '0/5 * * * * *',async ()=>{
                // console.log('timef:', new Date().getSeconds()) 
                let waitDownload = await this.$model.mp3.getWaitDownloadMp3();
                // console.log(waitDownload,waitDownload?.keywords)
                if (!waitDownload?.keywords) { 
                    return;
                }
                let id = waitDownload.id;
                // console.log(waitDownload)
                let downEntity = await get_music(id, waitDownload.keywords);
                 
                await this.$model.mp3.db.update({ empty_search: (!downEntity ? 1 : 0) }, { id });
                if (!downEntity) { 
                    return;
                }
                let donwOk = true;
                try { 
                    // 下载中
                    await this.$model.mp3.db.update({ download_status: 2 }, { id }); 
                    await downloadMp3(downEntity);
                } catch (e) {
                    console.log(e)
                    donwOk = false;
                    await this.$model.mp3.db.update({ download_status: 0 }, { id });
                }
                if (donwOk) { 
                    await this.$model.mp3.db.update(downEntity,{id})
                    // 下载完成
                    await this.$model.mp3.db.update({ download_status: 1 }, { id });

                    try { 
                        load(`${downEntity.save_dir}/${downEntity.file_name}`).then( async (res) => {
                            //获取音频时长
                            let duration = res.duration;
                            console.log('mp3 duration..:', duration)
                            await this.$model.mp3.db.update({
                                duration,
                                size: res.length,
                                add_time: this.$utils.time()
                            }, { id });
                        });
                    } catch (ex) {
                        console.log(ex)
                     }
                }
                await this.$model.mp3.db.where({id}).inc('try_down_count')
            }); 
        } catch (e) { 
            console.log(e)
        }
     }
}

module.exports = Mp3;